<?php
/**
 * 竞标项目控制器
 */

namespace app\admin\controller;

use app\admin\traits\AdminSettingForm;
use app\admin\traits\SettingContent;
use app\common\model\Brand;
use app\common\model\Cate;
use app\common\model\Company;
use app\common\model\Compute;
use app\common\model\Project;
use app\common\model\ProjectLog;
use app\common\model\Spec;
use app\common\model\Type;
use app\common\model\TypeLog;
use app\common\model\User;
use app\common\validate\ProjectValidate;
use Exception;
use http\Exception\RuntimeException;
use think\db\Query;
use think\facade\Config;
use think\Request;
use think\response\Json;

class ProjectController extends AdminBaseController {
	use AdminSettingForm;
	use SettingContent;
	protected array $authExcept = [
		'admin/project/type',
	];
	/**
	 * 列表
	 * @param Request $request
	 * @param Project $model
	 * @return string
	 * @throws Exception
	 */
	public function index(Request $request, Project $model): string {
		$param = $request->param();
		$data = $model->with(['cate'])->scope('where', $param)
			->paginate([
				'list_rows' => $this->admin['admin_list_rows'],
				'var_page' => 'page',
				'query' => $request->get(),
			]);
		// 关键词，排序等赋值
		$this->assign($request->get());

		$this->assign([
			'data' => $data,
			'page' => $data->render(),
			'total' => $data->total(),
			'status_list' => Project::STATUS_LIST,
			'cate_list' => Cate::select(),
		]);
		return $this->fetch();
	}

	/**
	 * 添加
	 * @param Request $request
	 * @param Project $model
	 * @param ProjectValidate $validate
	 * @return string|Json
	 * @throws Exception
	 */
	public function add(Request $request, Project $model, ProjectValidate $validate) {
		if ($request->isPost()) {
			//$param = $request->param();
			$param = $request->post();

			$param['content'] = $request->param(false)['content'];

			try {
				$param['detail'] = $this->getDetail($param);
			} catch (RuntimeException $exception) {
				return admin_error($exception->getMessage());
			}
			$validate_result = $validate->scene('admin_add')->check($param);
			if (!$validate_result) {
				return admin_error($validate->getError());
			}
			$config = Config::get('site.site');
			$param['end_time'] = date('Y-m-d  H:i:s', strtotime('+ ' . $config['end'] . 'minutes', strtotime($param['start_time'])));
			$result = $model::create($param);

			$url = URL_BACK;
			if (isset($param['_create']) && (int) $param['_create'] === 1) {
				$url = URL_RELOAD;
			}
			$company_param['cate'] = [$param['cate_id']];
			$company_list = Company::scope('ApiWhere', $company_param)->column('id');
			$user_list = User::whereIn('company_id', $company_list)->column('mobile');
// 			$sms_result = $this->send_sms('2053169', [$param['title'], $param['start_time']], $user_list);

			return $result ? admin_success('添加成功', [], $url) : admin_error();
		}
		$this->assign([
			'cate_list' => Cate::where('status', 1)->select(),
			'status_list' => Project::STATUS_LIST,
			'win_list' => Project::WIN_LIST,
			'spec_list' => Spec::select(),
			'brand_list' => Brand::select(),
		]);

		return $this->fetch();
	}
	public function add2(Request $request, Project $model, ProjectValidate $validate) {
		if ($request->isPost()) {
			//$param = $request->param();
			$param = $request->post();

			$param['content'] = $request->param(false)['content'];

			try {
				$param['detail'] = $this->getDetail($param);
			} catch (RuntimeException $exception) {
				return admin_error($exception->getMessage());
			}
			$validate_result = $validate->scene('admin_add')->check($param);
			if (!$validate_result) {
				return admin_error($validate->getError());
			}
			$config = Config::get('site.site');
			$param['end_time'] = date('Y-m-d  H:i:s', strtotime('+ ' . $config['end'] . 'minutes', strtotime($param['start_time'])));
			$result = $model::create($param);

			$url = URL_BACK;
			if (isset($param['_create']) && (int) $param['_create'] === 1) {
				$url = URL_RELOAD;
			}
			$company_param['cate'] = [$param['cate_id']];
			$company_list = Company::scope('ApiWhere', $company_param)->column('id');
			$user_list = User::whereIn('company_id', $company_list)->column('mobile');
// 			$sms_result = $this->send_sms('2053169', [$param['title'], $param['start_time']], $user_list);

			return $result ? admin_success('添加成功', [], $url) : admin_error();
		}
		$param = $request->param();
		if (isset($param['id'])) {
			$compute = Compute::whereIn('id', $param['id'])->select()->toArray();
			foreach ($compute as $key => $value) {
				$compute[$key]['type'] = Type::where('id', $value['type_id'])->value('name');
				$compute[$key]['brand'] = Brand::where('id', $value['brand_id'])->value('name');
				$compute[$key]['spec'] = Spec::where('id', $value['spec_id'])->value('name');
				$compute[$key]['compute_id'] = $value['id'];
			}

		} else {
			$compute = [];
		}
		$this->assign([
			'cate_list' => Cate::where('status', 1)->select(),
			'status_list' => Project::STATUS_LIST,
			'win_list' => Project::WIN_LIST,
			'spec_list' => Spec::select(),
			'brand_list' => Brand::select(),
			'compute' => $compute,
		]);

		return $this->fetch();
	}
	/**
	 * 修改
	 * @param $id
	 * @param Request $request
	 * @param Project $model
	 * @param ProjectValidate $validate
	 * @return string|Json
	 * @throws Exception
	 */
	public function edit($id, Request $request, Project $model, ProjectValidate $validate) {
		$data = $model->findOrEmpty($id);
		if ($request->isPost()) {
			$param = $request->param();

			$param['content'] = $request->param(false)['content'];

			try {
				$param['detail'] = $this->getDetail($param);
			} catch (RuntimeException $exception) {
				return admin_error($exception->getMessage());
			}
			$validate_result = $validate->scene('admin_add')->check($param);
			if (!$validate_result) {
				return admin_error($validate->getError());
			}
			$param['end_time'] = date('Y-m-d H:i:s', strtotime('+ ' . $config['end'] . 'minutes', strtotime($param['start_time'])));
			$result = $data->save($param);

			return $result ? admin_success('修改成功', [], URL_BACK) : admin_error('修改失败');
		}

		$this->assign([
			'data' => $data,
			'cate_list' => Cate::where('status', 1)->select(),
			'status_list' => Project::STATUS_LIST,
			'win_list' => Project::WIN_LIST,
			'spec_list' => Spec::select(),
			'brand_list' => Brand::select(),
		]);

		return $this->fetch('add');
	}

	/**
	 * 删除
	 * @param mixed $id
	 * @param Project $model
	 * @return Json
	 */
	public function del($id, Project $model): Json {
		$check = $model->inNoDeletionIds($id);
		if (false !== $check) {
			return admin_error('ID为' . $check . '的数据不能被删除');
		}

		$result = $model::destroy(static function ($query) use ($id) {
			/** @var Query $query */
			$query->whereIn('id', $id);
		});

		return $result ? admin_success('删除成功', [], URL_RELOAD) : admin_error('删除失败');
	}
	public function type($cate_id, $id, Type $model) {
		$list = $model::where('cate_id', $cate_id)->where('parent_id', '<>', 0)->select();
		$data = Project::find($id);
		$this->assign([
			'type_list' => $list,
			'data' => $data,
		]);
		return $this->fetch();
	}
	public function type_log($type_id) {
		$log = TypeLog::where('type_id', $type_id)->whereDay('create_time')->findOrEmpty();
		if ($log->isEmpty()) {
			return json(['price' => 0]);
		} else {
			return json(['price' => $log['price']]);
		}
	}
	public function disable($id, Project $model): Json {
		$result = $model->whereIn('id', $id)->update(['status' => 3]);
		ProjectLog::whereIn('project_id', $id)->update(['status' => 3]);
		return $result ? admin_success('操作成功', [], URL_RELOAD) : admin_error();
	}

}
